package uk.co.hs.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Intercepts a handler to put a user attribute into the session.
 */
public class UserInterceptor implements HandlerInterceptor
{
  private static final String LOGGED_IN_USERNAME = "loggedInUsername";

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor
   * #preHandle(javax.servlet.http.HttpServletRequest,
   *            javax.servlet.http.HttpServletResponse,
   *            java.lang.Object)
   * {@inheritDoc}
   */
  public boolean preHandle(HttpServletRequest aRequest,
                           HttpServletResponse aResponse,
                           Object aHandler) throws Exception
  {
  	if (aRequest.getSession().getAttribute(LOGGED_IN_USERNAME) == null)
    {
      if (SecurityContextHolder.getContext().getAuthentication() != null)
      {
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();
        if (userName.equals("anonymousUser"))
        {
          userName = "";
        }
        aRequest.getSession().setAttribute(LOGGED_IN_USERNAME, userName);
      }
    }
  	return true;
  }

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor
   * #postHandle(javax.servlet.http.HttpServletRequest,
   *             javax.servlet.http.HttpServletResponse,
   *             java.lang.Object,
   *             org.springframework.web.servlet.ModelAndView)
   * {@inheritDoc}
   */
  public void postHandle(HttpServletRequest aRequest,
                         HttpServletResponse aResponse,
                         Object aHandler,
                         ModelAndView aModelAndView) throws Exception
  { }

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor
   * #afterCompletion(javax.servlet.http.HttpServletRequest,
   *                  javax.servlet.http.HttpServletResponse,
   *                  java.lang.Object, java.lang.Exception)
   * {@inheritDoc}
   */
  public void afterCompletion(HttpServletRequest aRequest,
                              HttpServletResponse aResponse,
                              Object aHandler,
                              Exception aException) throws Exception
  { }
}
